'use strict';

const Service = require('egg').Service;
const moment = require('moment');

class UserService extends Service {

  async login(uname, pwd) {
    const { app } = this;
    const res = await app.mysql.query(`select id from users where uname='${uname}' and pwd='${pwd}'`);
    let id = -1;
    if (JSON.stringify(res) !== '[]') {
      id = res[0].id;
    }
    return id;
  }

  // 联合查询 users union dparts
  async getUsersUdparts() {
    const { app } = this;
    const users = await app.mysql.query('select u.id,u.uname,u.cn,u.phone,u.ctime,d.dpart_name from users as u left join dparts as d on u.dpart = d.dpart_id order by u.dpart');
    return users;
  }

  // 获取user
  async getUser(id) {
    const { app } = this;
    const user = await app.mysql.query(`select id,uname,cn,dpart,state,sex,phone,email from users where id = ${id}`);
    return user;
  }

  // 删除user
  async delUser(id) {
    const { app } = this;
    return await app.mysql.query(`delete from users where id=${id}`);
  }

  // 新增user
  async addUser(uname, pwd, cn, dpart, state, sex, phone, email) {
    const { app } = this;
    app.mysql.query(`insert into users values(default,"${uname}","${pwd}","${cn}",${dpart},${state},${sex},"${phone}","${email}","${moment(new Date()).format('YYYY-MM-DD HH:mm:ss')}")`);
  }

  // 修改user
  updateUser(pwd, cn, dpart, state, sex, phone, email, id) {
    const { app } = this;
    app.mysql.query(`update users set pwd="${pwd}", cn="${cn}", dpart=${dpart}, state=${state}, sex=${sex}, phone="${phone}", email="${email}" where id=${id}`);
  }

  // 搜索框查询
  async searchUsers(kw) {
    const { app } = this;
    const users = await app.mysql.query(`select u.id,u.uname,u.cn,u.phone,u.ctime,d.dpart_name from users as u left join dparts as d on u.dpart = d.dpart_id where u.cn like '%${kw}%' order by u.dpart`);
    return users;
  }
}

module.exports = UserService;
